#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QFileDialog>
#include <QFileInfo>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->BtnFilenameSel, &QPushButton::clicked, this, &MainWindow::onBtnFilenameSelClicked);
    connect(ui->BtnFileWrite, &QPushButton::clicked, this, &MainWindow::onBtnFileWriteClicked);
    connect(ui->BtnSelWriteFolder, &QPushButton::clicked, this, &MainWindow::onBtnSelWriteFolderClicked);

    // QByteArray a = QByteArray::number(56386,10);
    // a.resize(16);
    // qDebug() << a.toHex(' ').toUpper();
    // qDebug() << a.toUInt();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onBtnFilenameSelClicked()
{
    m_filename = QFileDialog::getOpenFileName(
        this,
        tr("open a file."),
        "E:/",
        tr("Binary files(*.bin *.raw);;symbols(*.srec *.s19);;All files(*.*)"));
    if (m_filename.isEmpty())
    {
        QMessageBox::warning(this, "Warning!", "filename is empty");
    }
    else
    {
        ui->LineEdtFilename->setText(m_filename);
        QFile file(m_filename);

        if(!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::warning(this, "error!", "Failed to open the file!");
            return;
        }
        m_fileArr = file.readAll();
        file.close();

        m_fileLen = m_fileArr.size();
        QString str1 = QString("文件长度：%1 Bytes").arg(QString::number(m_fileLen));
        ui->txtLabFile->setText(str1);

        QString str2;
        for(qsizetype i = 0; i < m_fileLen; i++)
        {
            if(i % 16 == 0)
            {
                if(i)
                {
                    ui->textEditBin->append(str2);
                }
                //
                str2 = QStringLiteral("%1\t\t").arg(i, 8, 16, QLatin1Char('0')).toUpper();
            }
            else if(i % 8 == 0)
            {
                str2 += "\t";
            }
            else
            {
                str2 += " ";
            }
            str2 += QString("%1").arg(m_fileArr.at(i)&0xff,2,16, QLatin1Char('0')).toUpper();
        }
        ui->textEditBin->append(str2);
    }
}

void MainWindow::onBtnFileWriteClicked()
{
    bool  ok;
    m_appVer = ui->LineEdtAPPVer->text().toUInt(&ok);

    if(!ok)
    {
        QMessageBox::critical(this, "error!", "APP version is not a unsigned number!");
        return;
    }

    m_operatorMsg = ui->LineEdtOPMsg->text().toUtf8();
    if(m_operatorMsg.isEmpty())
    {
        QMessageBox::critical(this, "error!", "operator message is empty!");
        return;
    }

    if(m_filename.isEmpty())
    {
        QMessageBox::critical(this, "error!", "APP bin file is not select!");
        return;
    }

    if(m_WrFolderPath.isEmpty())
    {
        QMessageBox::critical(this, "error!", "No folder for writing has been selected!");
        return;
    }

    QFileInfo fileinfo(m_filename);
    QString basename = fileinfo.baseName();
    basename += ".boot";

    m_WrFolderPath += basename;  // 完整的写入文件名

    // 如果目标文件已存在，删除它
    if (QFile::exists(m_WrFolderPath)) {
        QFile::remove(m_WrFolderPath);
    }

    //初始化时加载文件路径
    QFile WrFile(m_WrFolderPath);
    //如果文件不存在，则创建并打开该文件
    if(!WrFile.open(QIODevice::ReadWrite | QIODevice::Append))
    {
        QMessageBox::warning(this, "error!", "Failed to open the file!");
        return;
    }

    QByteArray vnumber = QByteArray::number(m_appVer,10);
    if(vnumber.size() < 16)// 版本号保存16字节
    {
        vnumber.append(16-vnumber.size(),0);
    }
    else
    {
        vnumber.resize(16);
    }
    if(m_operatorMsg.size() < 32)// 操作员信息保存32字节
    {
        m_operatorMsg.append(32-m_operatorMsg.size(),0);
    }
    else
    {
        m_operatorMsg.resize(32);
    }

    QByteArray applenArr = QByteArray::number(m_fileLen,10);
    if(applenArr.size() < 16)// 版本号保存16字节
    {
        applenArr.append(16-applenArr.size(),0);
    }
    else
    {
        applenArr.resize(16);
    }

    vnumber.append(m_operatorMsg);
    vnumber.append(applenArr);
    WrFile.write(vnumber);
    WrFile.write(m_fileArr.data(),m_fileLen);

    WrFile.close();

    QMessageBox::information(this, "message!", "write success!");
}

void MainWindow::onBtnSelWriteFolderClicked()
{
    m_WrFolderPath = QFileDialog::getExistingDirectory(this, QStringLiteral("选择目录"), "D:/");
    if (!m_WrFolderPath.isEmpty()) {
        ui->txtLabWrFolder->setText(m_WrFolderPath);
    }
}
